package com.ylx.web;

import com.ylx.pojo.User;
import com.ylx.service.UserService;
import com.ylx.service.UserServiceIpml;
import com.ylx.util.UploadFileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceIpml();


    public void updateTouXiang (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        UserService us = new UserServiceIpml();

        //要修改头像
        String zp = UploadFileUtil.uploadFile(request, response);
        //上传成功后需要将照片的名字保存到数据库中
        //获取登录的用户账号
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("us");
        user.setZp(zp);
        System.out.println("--->" + user);
        int i = us.updateZp(user);
        if (i > 0) {
            System.out.println("头像修改成功");
            //将修改后的xsb重写放到session中
            session.setAttribute("us", user);
            //拼接前端的json格式
            String jsonrs = "{\"code\":0,\"msg\":\"\",\"data\":\"\"}";
            System.out.println(jsonrs);
            //输出在浏览器
            PrintWriter out = response.getWriter();
            out.println(jsonrs);
        }
    }

    public void register (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        UserService userService = new UserServiceIpml();
        User user1 = userService.selectByUsername(username);

        if (user1 == null) {
            userService.add(user);
            request.setAttribute("login", "注册成功请登录");
            request.getRequestDispatcher("login.jsp").forward(request, response);

        } else {
//     数据库中有这个用户
            request.setAttribute("error", "用户已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);

        }


    }
}